﻿package nl.sanity.net
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.EventDispatcher;
	import flash.net.URLVariables;
	import flash.net.URLRequest;
	import flash.net.URLLoader;
	import flash.net.URLRequestMethod;
	import flash.net.URLLoaderDataFormat;
	
	import nl.sanity.events.ServerInterfaceEvent;
	
	import nl.sanity.debug.LogConsole;
	
	/**
	 * ServerInterface
	 * Interface to manage server calls
	 * 
	 * @langversion ActionScript 3
	 *
	 * @author M.P. Bartnig / A. Gosman
	 * @since  28/03/2009
	 */
	public class ServerInterface extends EventDispatcher
	{
		public static const NAME					: String	= "ServerInterface";
		
		public static var DEBUG						: Boolean	= false;
		
		// Defaults
		public static const DEFAULT_INTERFACE_URL	: String	= "rpc.php";
		public static const DEFAULT_METHOD			: String	= "POST";
		public static const DEFAULT_DATA_FORMAT		: String	= "TEXT"; // TEXT or VARIABLES
		public static const DEFAULT_RPC_FORMAT		: String 	= "purexml";
		public static const DEFAULT_TIMESTAMP		: Boolean 	= true;
		
		protected var _command 						: String;
		protected var _interfaceURL					: String;
		protected var _method						: String;
		protected var _dataFormat					: String;
		protected var _rpcFormat					: String;
		protected var _timeStamp					: Boolean;
		
		// Loaded data
		protected var _data							: Object;
		protected var _extraData					: Object;
		
		private var _urlLoader						: URLLoader;
		
		// --- CONSTRUCTOR ----------------------------------------

		public function ServerInterface ()
		{
			// Defaults
			_interfaceURL	= ServerInterface.DEFAULT_INTERFACE_URL;
			_method			= ServerInterface.DEFAULT_METHOD;
			_dataFormat		= ServerInterface.DEFAULT_DATA_FORMAT;
			_rpcFormat		= ServerInterface.DEFAULT_RPC_FORMAT;
			_timeStamp		= ServerInterface.DEFAULT_TIMESTAMP;
		}
		
		public function sendAndLoad ( command:String = "", vars:Object = null ):void
		{
			_command						= command;
			
			var varsToSend:URLVariables		= new URLVariables();
			
			// Set command
			if ( command != "" )
			{
				varsToSend.command = command;
			}
			
			if ( _interfaceURL.indexOf( "rpc.php" ) != -1 )
			{
				varsToSend._format = _rpcFormat;
			}
			
			if ( _timeStamp )
			{
				varsToSend.ts = new Date().getTime().toString();
			}
			
			if ( DEBUG ) LogConsole.info ( NAME + ".sendAndLoad" );
			
			// Push variables
			for ( var key:String in vars )
			{
				varsToSend [ key ] = vars [ key ];
			}
			
			if ( DEBUG )
			{
				for ( var p:String in varsToSend )
				{
					LogConsole.info ( "\t " + p + ": " + varsToSend [ p ] );
				}
			}
			
		    var urlRequest:URLRequest	= new URLRequest( _interfaceURL );
		    urlRequest.data				= varsToSend;
		    urlRequest.method			= URLRequestMethod[ _method ];
		   
		    _urlLoader					= new URLLoader()
		    _urlLoader.dataFormat		= URLLoaderDataFormat[ _dataFormat ];
		    
		    _urlLoader.addEventListener ( Event.COMPLETE, onSendComplete, false, 0, false );
		    _urlLoader.addEventListener ( IOErrorEvent.IO_ERROR, onSendIOError, false, 0, false );
		    
			_urlLoader.load ( urlRequest );
		}
		
		// --- PROTECTED FUNCTIONS ----------------------------------------

		protected function onSendComplete( event:Event ):void
		{
			if ( DEBUG ) LogConsole.info ( NAME + ".onSendComplete" );
			
			_data = event.target.data;
			
			dispatchEvent ( new ServerInterfaceEvent( ServerInterfaceEvent.ON_COMPLETE, _data ) );
		}
		
		protected function onSendIOError( oEvent:IOErrorEvent ):void
		{
			if ( DEBUG ) LogConsole.info ( NAME + ".onSendIOError" );
			
			dispatchEvent ( new ServerInterfaceEvent( ServerInterfaceEvent.ON_ERROR ) ); 
		}
		
		// --- GETTERS / SETTERS ------------------------------------------------------------------------------------
		
		public function get url():String
		{
			return _interfaceURL;
		}
		public function set url ( sURL:String ):void
		{
			_interfaceURL	= sURL;
		}
		
		public function get method():String
		{
			return _method;
		}
		public function set method ( value:String ):void
		{
			_method	= value;
		}
		
		public function get dataFormat():String
		{
			return _dataFormat;
		}
		public function set dataFormat ( value:String ):void
		{
			_dataFormat	= value;
		}
		
		public function get rpcFormat():String
		{
			return _rpcFormat;
		}
		public function set rpcFormat ( value:String ):void
		{
			_rpcFormat	= value;
		}
		
		public function get command():String 
		{ 
			return _command; 
		}
		public function set command( value:String ):void 
		{
			_command = value;
		}
		
		public function get data():Object
		{
			return _data;
		}
		
		public function get timestamp():Boolean
		{
			return _timeStamp;
		}
		
		public function set timestamp( value:Boolean ):void 
		{
			_timeStamp = value;
		}
		
		// use the 'extraData' property to store data inside the ServerInterface that is needed again in the serverreply event handler.
		public function get extraData():Object 
		{ 
			return _extraData; 
		}
		public function set extraData( value:Object ):void 
		{
			_extraData = value;
		}
		
	}
}